package com.raylu.day02basic;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Example6TypeErasing {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements("white", "black", "gray")
                .flatMap(new MyFlatMap())
                .print();

        env
                .fromElements("white", "black", "gray")
                .flatMap((String value, Collector<String> out) -> {
                    if (value.equals("white")) {
                        out.collect(value);
                    } else if (value.equals("black")) {
                        out.collect(value);
                        out.collect(value);
                    }
                })
                // 类型擦除成了Collector<Object>
                // 需要提供flatMap输出的类型注解
                .returns(Types.STRING)
                .print();

        // 不推荐
        env
                .fromElements("white", "black", "gray")
                .flatMap((FlatMapFunction<String, String>) (value, out) -> {
                    if (value.equals("white")) {
                        out.collect(value);
                    } else if (value.equals("black")) {
                        out.collect(value);
                        out.collect(value);
                    }
                })
                .returns(Types.STRING)
                .print();

        env.execute();
    }

    public static class MyFlatMap implements FlatMapFunction<String, String> {
        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            if (value.equals("white")) {
                out.collect(value);
            } else if (value.equals("black")) {
                out.collect(value);
                out.collect(value);
            }
        }
    }
}
